<?php

namespace app\api\controller;

use addons\shopro\service\order\OrderDispatch;
use addons\shopro\service\user\User as UserService;
use addons\shopro\service\Wallet as WalletService;
use app\admin\model\Children;
use app\admin\model\market\Acceleration;
use app\admin\model\shopro\goods\SkuPrice;
use app\admin\model\shopro\order\Action;
use app\admin\model\shopro\order\Order;
use app\admin\model\shopro\order\OrderItem;
use app\admin\model\shopro\user\Silverlog;
use app\admin\model\shopro\user\WalletLog;
use app\common\controller\Api;
use app\common\model\GoldenLog;
use app\common\model\GoldLog;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use app\common\model\shopro\DividendLog;
use app\common\model\shopro\ReleaseAccelerateLogModel;
use app\common\model\shopro\ReleaseAccelerateMarketplaceLogModel;
use app\common\model\shopro\ReleaseLog;
use app\common\model\shopro\Shop;
use app\common\model\User;
use app\common\model\Userchildren;
use app\common\model\UserStaticLogModel;
use app\common\model\UserTransformLog;
use fast\Random;
use think\Db;
use think\exception\HttpResponseException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    public function scse(){
//        $userData = db('user')->field('id,principal,golden,silver,gold,score')->select();
//        foreach ($userData as $k=>$v){
//            $up = [];
//            if($v['principal'] > 0){
//                $up['principal']  = round($v['principal'] * 480,2);
//            }
//            if($v['golden'] > 0){
//                $up['golden']  = round($v['golden'] * 480,2);
//            }
//            if($v['silver'] > 0){
//                $up['silver']  = round($v['silver'] * 480,2);
//            }
//            if($v['gold'] > 0){
//                $up['gold']  = round($v['gold'] * 480,2);
//            }
//            if($v['score'] > 0){
//                $up['score']  = round($v['score'] * 480,2);
//            }
//            if($up){
//                var_dump($up);
//                var_dump($v['id']);
//               $r = db('user')->where(['id'=>$v['id']])->update($up);
//               var_dump($r);
//            }
//        }
//        var_dump($userData);
//        exit();
        $order = Order::where(['id'=>570])->find();
        $user = \app\admin\model\User::where(['id'=>$order['user_id']])->find();
       $res=  $this->fenyong($order, $user);

        var_dump($res);
//        jicha($user, $order['order_amount'], $user->level);exit();
//        exit();
//
//        var_dump(cache('next_rebate_time',1726588801));
//        var_dump(86400 * config('site.settlement_day') + strtotime('today'));exit();
//        $userModel        = new User();
//        $model            = new UserStaticLogModel();
//        $user_idArr       = $userModel->where('principal', '>', 0)->column('id');
//        $data             = $model->with(['user'])->where('status', '=', 1)->whereIn('user_id',
//            $user_idArr)->where('rebate_time', '<', time())->select();
//        dump($model->getLastSql());
//        var_dump($data);exit();
//        dump(strtotime(date('Y-m-d',30*86400+time())));exit();
//        $partner_day = 7;
//        $sta_time      = strtotime('-'.$partner_day.' days', strtotime(date('Y-m-d')));
//        $userModel        = new User();
//        $model            = new UserStaticLogModel();
//        $rebate_time = 86400*$partner_day +time();
//        dump($rebate_time);exit();
//        $user_idArr       = $userModel->where('principal', '>', 0)->column('id');
//        $data  = $model->with(['user'])->where('status','=',1)->whereIn('user_id', $user_idArr)->where('rebate_time','<',time())->select();
//        $order = Order::where(['id'=>266])->with(['items'])->find();
//        $user = User::where(['id'=>$order->user_id])->find();
//        // 添加消费金额
////        UserService::consume($user, $order['order_amount']);
//        jicha($user, $order['order_amount'], $user->level);
//        $id_arr = User::where(['id'=>['neq','761']])->delete();
//        MoneyLog::whereIn('user_id',$id_arr)->delete();
//        Silverlog::whereIn('user_id',$id_arr)->delete();
//        ScoreLog::whereIn('user_id',$id_arr)->delete();
//        GoldLog::whereIn('user_id',$id_arr)->delete();
//       $r = Userchildren::where('member_id','<>',761)->delete();
//       dump($r);
//        $ids_arr =  Userchildren::where('member_id',761)->column('children_id');
//        $userModel = new User();
//       $r= $userModel->whereNotIn('id', $ids_arr)->delete();
//        dump($r);
    }


    /**
     * @menu 分积分
     * @Author:男人的坏
     * @Date:2024-04-15 15:22
     */
    public function fenyong($order, $user)
    {
        $goodsModel        = new \app\admin\model\shopro\goods\Goods();
        $gift_score        = 0;
        $gift_silver       = 0;
        $principal_score   = 0;
        $parent_user_info  = '';
        $parent_user_money = 0;
//        dump($user->parent_user_id);
        if ($user->parent_user_id) {
            $parent_user_info = \app\common\model\User::where(['id' => $user->parent_user_id])->field('id,score,principal,level,is_marketplace,parent_user_id')->find();
        }
        $two_user_money = 0;
        $two_user_info  = '';
        if (!empty($parent_user_info->parent_user_id)) {
            $two_user_info = \app\common\model\User::where(['id' => $parent_user_info->parent_user_id])->field('id,score,principal,level,is_marketplace')->find();
        }
        $user_ids          = \app\common\model\User::where(['parent_user_id' => $user->id])->column('id');
//        $is_shichang       = \app\admin\model\shopro\order\Order::where(['status' => 'paid'])->whereIn('user_id',
//            $user_ids)->count();
        $ziGou       = \app\admin\model\shopro\order\Order::where(['status' => 'paid'])->where('user_id',
            $user->id)->count();
        $parent_score      = 0;
        $golen_scale       = 0;
        $slive_scale       = 0;
        $principal_score   = 0;
        $shop_parent_score = 0;
        $isCard            = true;
        $inser             = [];
        $isJc  = 0;
        foreach ($order['items'] as $k => $v) {
            $goodsInfo = $goodsModel->where(['id' => $v->goods_id])->find();
            if ($goodsInfo) {
                $isJc = $goodsInfo['check_piji'];
                if ($goodsInfo['type'] == 'normal') {
                    if ($ziGou) {
                        $marketplace_times = $goodsInfo->fugou_marketplace_times;
                        $one_scale         = $goodsInfo->fugou_one_scale;
                        $two_scale         = $goodsInfo->fugou_two_scale;
                    } else {
                        $marketplace_times = $goodsInfo->marketplace_times;
                        $one_scale         = $goodsInfo->one_scale;
                        $two_scale         = $goodsInfo->two_scale;
                    }
                    $isCard            = false;
                    $goods_golen_scale = $goodsInfo['golen_scale'];
                    if ($goods_golen_scale) {
                        $golen_scale = $goods_golen_scale / 100;        //金豆比例
                        $slive_scale = (100 - $goods_golen_scale) / 100;//银豆比例
                    }
                    if ($order['pay_fee'] > 0) {
                        if ($goodsInfo->is_principal_score > 0) {
                            $principal_score    = bcmul($order['order_amount'], $goodsInfo->is_principal_score);
                            $userTransformArray = ['user_id' => $user->id, 'goods_id' => $v->goods_id];
                            $userTransformInfo  = UserTransformLog::where($userTransformArray)->find();
                            if ($userTransformInfo) {
                                $userTransformInfo->setInc('principal', $principal_score);
                            } else {
                                $userTransformArray['principal'] = $principal_score;
                                UserTransformLog::create($userTransformArray);
                            }
                        }
                        if ($marketplace_times > 0) {
                            $gift_score = bcmul($order['order_amount'], $marketplace_times);
                            if ($principal_score > 0) {
                                UserStaticLogModel::create([
                                    'user_id'     => $user->id,
                                    'order_id'    => $order['id'],
                                    'goods_id'    => $v->goods_id,
                                    'money'       => $principal_score,
                                    'rebate_time' => strtotime(date('Y-m-d', 31 * 86400 + time()))
                                ]);
                            }
                        }
                    }
                    if ($goodsInfo->type == 'normal') {
                        if ($parent_user_info) {
                            $parent_user_money = bcmul($order['order_amount'], ($one_scale / 100), 2);
                            if ($parent_user_info->is_marketplace == 0) {
                                $goods_id = OrderItem::where(['user_id' => $parent_user_info->id])->value('goods_id');
                                if ($goods_id) {
                                    $parent_user_goods = \app\admin\model\shopro\Goods::where([
                                        'id'   => $goods_id,
                                        'type' => 'normal'
                                    ])->find();
                                    if($ziGou){
                                        if (!empty($parent_user_goods->fugou_marketplace_times)) {
                                            $parent_score                     = bcmul($parent_user_info->principal,
                                                $parent_user_goods->fugou_marketplace_times);
                                            $parent_user_info->is_marketplace = 1;
                                            $parent_user_info->save();

                                        }
                                    }else{
                                        if (!empty($parent_user_goods->marketplace_times)) {
                                            $parent_score                     = bcmul($parent_user_info->principal,
                                                $parent_user_goods->marketplace_times);
                                            $parent_user_info->is_marketplace = 1;
                                            $parent_user_info->save();

                                        }
                                    }

                                }
                            }
                        }
                        if ($two_user_info) {
                            $two_user_money = bcmul($order['order_amount'], ($two_scale / 100), 2);
                        }
                    }
                    //赠送银豆
                    if ($goodsInfo->silver_type == 'silver_scale_type') {
                        $gift_silver += bcmul($v->pay_fee, ($goodsInfo->silver_type_num / 100), 2);
                    } elseif ($goodsInfo->firepower_type == 'silver_immobilization') {
                        $gift_silver = $goodsInfo->silver_type_num;
                    }
                } elseif ($goodsInfo['type'] == 'card') {
                    $shopParentId    = Shop::where(['id' => $order['shop_id']])->value('parent_id');
                    if($shopParentId){
                        $shop_parent_user_info = \app\common\model\User::where(['id'=>$shopParentId])->find();
                        if($shop_parent_user_info){
                            if ($order['pay_fee'] > 0 && $shop_parent_user_info) {
                                $shop_recommended = bcmul($order['pay_fee'], ($goodsInfo->buy_recommended / 100), 2);
                                if ($shop_recommended > 0) {
                                    $shop_parent_score      += $shop_recommended;
                                }
                            }
                        }
                    }
                }
            }
            if($shop_parent_score > 0){
                return WalletService::change($shop_parent_user_info['id'], 'golden', $shop_parent_score, 'jhbt','','进货区补贴');
            }
            //进货商品没有自购奖励
            if (!$isCard) {
                //倍数积分
                $params['id']  = $order['user_id'];
                $params['ext'] = ['order_id' => $order['id']];
                if ($gift_score) {
                    $params['type']   = 'score';
                    $params['amount'] = $gift_score;
                    $params['memo']   = '自购奖励';
                    if ($params['amount'] > 0) {
                        Db::transaction(function () use ($params) {
                            return WalletService::change($params['id'], $params['type'], $params['amount'], 'release',
                                $params['ext'],
                                $params['memo']);
                        });
                    }

                }
            }

            if ($parent_score > 0) {
                Db::transaction(function () use ($parent_user_info, $parent_score, $order) {
                    return WalletService::change($parent_user_info->id, 'score', $parent_score, 'release',
                        ['order_id' => $order['user_id']],
                        '动态积分');
                });
                $parent_user_info->score += $parent_score;
            }
            //本金
            if ($principal_score > 0) {
                $params['type']   = 'principal';
                $params['amount'] = $principal_score;
                $params['memo']   = '自购奖励';
                Db::transaction(function () use ($params) {
                    return WalletService::change($params['id'], $params['type'], $params['amount'], 'order',
                        $params['ext'],
                        $params['memo']);
                });

            }
            //赠送银豆
            if ($gift_silver > 0) {
                $params['type']   = 'silver';
                $params['amount'] = $gift_silver;
                $params['memo']   = '自购奖励';
                Db::transaction(function () use ($params) {
                    return WalletService::change($params['id'], $params['type'], $params['amount'], 'order',
                        $params['ext'],
                        $params['memo']);
                });
            }
//            if ($parent_user_money > 0) {
//                if ($parent_user_info->principal >= $parent_user_money) {
//                    $this->RecommendedFenyong($parent_user_info, $parent_user_money, '推荐收益', 'principal', $golen_scale,
//                        $slive_scale);
//                } else {
//                    if ($parent_user_info->principal == 0) {
//                        if ($parent_user_info->score > 0) {
//                            if ($parent_user_info->score >= $parent_user_money) {
//                                $this->RecommendedFenyong($parent_user_info, $parent_user_money, '推荐收益', 'score',
//                                    $golen_scale, $slive_scale);
//                            } else {
//                                $this->RecommendedFenyong($parent_user_info, $parent_user_info->score, '推荐收益', 'score',
//                                    $golen_scale, $slive_scale);
//                            }
//                        }
//                    } else {
//                        $parent_user_money -= $parent_user_info->principal;
//                        $this->RecommendedFenyong($parent_user_info, $parent_user_info->principal, '推荐收益', 'principal',
//                            $golen_scale, $slive_scale);
//                        if ($parent_user_info->score >= $parent_user_money) {
//                            $this->RecommendedFenyong($parent_user_info, $parent_user_money, '推荐收益', 'score',
//                                $golen_scale, $slive_scale);
//                        } else {
//                            $this->RecommendedFenyong($parent_user_info, $parent_user_info->score, '推荐收益', 'score',
//                                $golen_scale, $slive_scale);
//                        }
//                    }
//
//                }
//            }
//
//            if ($two_user_money > 0) {
//                if ($two_user_info->principal >= $two_user_money) {
//                    $this->RecommendedFenyong($two_user_info, $two_user_money, '间推收益', 'principal', $golen_scale,
//                        $slive_scale);
//                } else {
//                    if ($two_user_info->principal == 0) {
//                        if ($two_user_info->score > 0) {
//                            if ($two_user_info->score >= $two_user_money) {
//                                $this->RecommendedFenyong($two_user_info, $two_user_money, '间推收益', 'score',
//                                    $golen_scale, $slive_scale);
//                            } else {
//                                $this->RecommendedFenyong($two_user_info, $two_user_info->score, '间推收益', 'score',
//                                    $golen_scale, $slive_scale);
//                            }
//                        }
//                    } else {
//                        $two_user_money -= $two_user_info->principal;
//                        $this->RecommendedFenyong($two_user_info, $two_user_info->principal, '间推收益', 'principal',
//                            $golen_scale, $slive_scale);
//                        if ($two_user_info->score >= $two_user_money) {
//                            $this->RecommendedFenyong($two_user_info, $two_user_money, '间推收益', 'score', $golen_scale,
//                                $slive_scale);
//                        } else {
//                            $this->RecommendedFenyong($two_user_info, $two_user_info->score, '间推收益', 'score',
//                                $golen_scale, $slive_scale);
//                        }
//                    }
//                }
//            }
//
            if ($order['order_amount'] > 0 && $isJc) {
                jicha($user, $order['order_amount'], $user->level);
            }
        }
    }


}
